import cv2
import base64
import json
import requests

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": "PcW3LlXU6HggcOiAYrcaLagr", "client_secret": "LkizYB9Sncdz3BR3vV8891UsTYEnMyNy"}
    return str(requests.post(url, params=params).json().get("access_token"))

def capture_image_and_convert_to_base64(on_key_press=True):
    if on_key_press:
        cv2.namedWindow("Press 'o' to Capture")
        cap = cv2.VideoCapture(0)

        got_frame = False
        while not got_frame:
            _, frame = cap.read()
            cv2.imshow("Press 'o' to Capture", frame)

            key = cv2.waitKey(1) & 0xFF
            if key == ord('o'):
                got_frame = True
                break

        # 在关闭摄像头前确保保存按下 'o' 键时的最后一帧
        if got_frame:
            image_bgr = frame
        else:
            print("未成功获取到图像！")
            exit(1)

        cap.release()
        cv2.destroyAllWindows()

    # 不论是否在循环内，均从此处开始对图像进行处理
    image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
    
    # 转换为JPEG格式并压缩
    _, image_jpg_encoded = cv2.imencode('.jpg', image_rgb, [cv2.IMWRITE_JPEG_QUALITY, 90])

    # 将JPEG编码转换为Base64格式
    image_base64 = base64.b64encode(image_jpg_encoded).decode('utf-8')

    return image_base64

def main():
    access_token = get_access_token()
    url = f"https://aip.baidubce.com/rest/2.0/face/v3/search?access_token={access_token}"

    # 等待用户按键后捕获照片并转换为Base64
    image_base64 = capture_image_and_convert_to_base64()

    payload = json.dumps({
        "group_id_list": "attendance001",
        "image_type": "BASE64",
        "image": image_base64
    })

    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.post(url, headers=headers, data=payload)

    print(response.text)

if __name__ == '__main__':
    main()